#include "Component/Room/RoomRegisterComponent.h"

#include "Subsystem/RoomManager/RoomManagerFunctionLibrary.h"
#include "Subsystem/RoomManager/RoomManagerSubsystem.h"

URoomRegisterComponent::URoomRegisterComponent()
{
}

void URoomRegisterComponent::BeginPlay()
{
	Super::BeginPlay();

	// 注意一定要给对应的 Actor 开启 GenerateOverlapEventsDuringLevelStreaming !!!
	AActor* Owner = GetOwner();
	ensureAlwaysMsgf(URoomManagerFunctionLibrary::IsValidRoomName(RoomName.RowName), TEXT("RoomName is invalid! at [%s] in [%s]"), *GetName(), *Owner->GetName());
	Owner->OnActorBeginOverlap.AddDynamic(this, &URoomRegisterComponent::OnActorEnterRoom);
	Owner->OnActorEndOverlap.AddDynamic(this, &URoomRegisterComponent::OnActorLeaveRoom);
}

void URoomRegisterComponent::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	AActor* Owner = GetOwner();
	Owner->OnActorBeginOverlap.RemoveDynamic(this, &URoomRegisterComponent::OnActorEnterRoom);
	Owner->OnActorEndOverlap.RemoveDynamic(this, &URoomRegisterComponent::OnActorLeaveRoom);

	// 结束的时候，需要将所有的 Actor 都离开房间
	TSet<AActor*> OverlappingActors;
	Owner->GetOverlappingActors(OverlappingActors);
	for (TObjectPtr<AActor> OverlappingActor : OverlappingActors)
	{
		OnActorLeaveRoom(Owner, OverlappingActor);
	}

	Super::EndPlay(EndPlayReason);
}

void URoomRegisterComponent::OnActorEnterRoom(AActor* OverlappedActor, AActor* OtherActor)
{
	if (URoomManagerSubsystem* RoomManagerSubsystem = GetWorld()->GetGameInstance()->GetSubsystem<URoomManagerSubsystem>())
	{
		RoomManagerSubsystem->AddActorToRoom(RoomName.RowName, GetOwner(), OtherActor);
	}
}

void URoomRegisterComponent::OnActorLeaveRoom(AActor* OverlappedActor, AActor* OtherActor)
{
	if (URoomManagerSubsystem* RoomManagerSubsystem = GetWorld()->GetGameInstance()->GetSubsystem<URoomManagerSubsystem>())
	{
		RoomManagerSubsystem->RemoveActorFromRoom(RoomName.RowName, GetOwner(), OtherActor);
	}
}
